<template>
  <div class="student-management">
    <!-- 页面标题 -->
    <div class="page-title">
      <h1>学生信息管理</h1>
    </div>
    
    <!-- 搜索条件 -->
    <div class="search-conditions">
      <el-form :model="searchForm" class="search-form">
        <!-- 第一行：搜索字段 -->
        <div class="search-fields">
          <el-form-item label="学号">
            <el-input
              v-model="searchForm.studentId"
              placeholder="请输入学号"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入姓名"
              clearable
              style="width: 150px"
            />
          </el-form-item>
          <el-form-item label="专业">
            <el-select
              v-model="searchForm.major"
              placeholder="请选择专业"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="major in majorOptions"
                :key="major.value"
                :label="major.label"
                :value="major.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="班级">
            <el-select
              v-model="searchForm.className"
              placeholder="请选择班级"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="className in classOptions"
                :key="className.value"
                :label="className.label"
                :value="className.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="status in statusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- 第二行：操作按钮 -->
        <div class="search-actions">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </el-form>
    </div>
    
    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button 
        v-if="canCreate('student-management')" 
        type="primary" 
        @click="showAddDialog"
      >
        <el-icon><Plus /></el-icon>
        新增学生
      </el-button>
      <!-- 批量删除功能已屏蔽 -->
      <!-- <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button> -->
    </div>
    
    <!-- 学生信息列表 -->
    <div class="student-list">
      <el-table
        v-loading="tableLoading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="studentId" label="学号" min-width="120" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="gender" label="性别" min-width="80" />
        <el-table-column prop="major" label="专业" min-width="150" />
        <el-table-column prop="className" label="班级" min-width="120" />
        <el-table-column prop="phone" label="电话" min-width="130" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="canEdit('student-management')" 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="canDelete('student-management')" 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <span class="total-info">共{{ pagination.total }}条记录</span>
      </div>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentId">
              <el-input v-model="formData.studentId" :disabled="isEdit" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="formData.gender" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="formData.birthDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="专业" prop="major">
              <el-select v-model="formData.major" style="width: 100%">
                <el-option
                  v-for="major in majorOptions"
                  :key="major.value"
                  :label="major.label"
                  :value="major.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="className">
              <el-select v-model="formData.className" style="width: 100%">
                <el-option
                  v-for="className in classOptions"
                  :key="className.value"
                  :label="className.label"
                  :value="className.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入学时间" prop="enrollmentDate">
              <el-date-picker
                v-model="formData.enrollmentDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" style="width: 100%">
                <el-option
                  v-for="status in statusOptions"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Plus,
  Search,
  Refresh,
  Download,
  Upload,
  Delete,
  Edit
} from '@element-plus/icons-vue'
import {
  getStudentList,
  addStudent,
  updateStudent,
  deleteStudent,
  batchDeleteStudents
} from '@/api/student'
import { canCreate, canEdit, canDelete } from '@/utils/permission'

export default {
  name: 'StudentManagement',
  components: {
    User,
    Plus,
    Search,
    Refresh,
    Download,
    Upload,
    Delete,
    Edit
  },
  setup() {
    const formRef = ref()
    const tableLoading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const selectedRows = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      studentId: '',
      name: '',
      major: '',
      className: '',
      status: ''
    })
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 表格数据
    const tableData = ref([])
    
    // 表单数据
    const formData = reactive({
      id: null,
      studentId: '',
      name: '',
      gender: '',
      birthDate: '',
      major: '',
      className: '',
      phone: '',
      email: '',
      enrollmentDate: '',
      status: '在校'
    })
    
    // 表单验证规则
    const formRules = {
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' },
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      birthDate: [
        { required: true, message: '请选择出生日期', trigger: 'change' }
      ],
      major: [
        { required: true, message: '请选择专业', trigger: 'change' }
      ],
      className: [
        { required: true, message: '请输入班级', trigger: 'blur' }
      ],
      enrollmentDate: [
        { required: true, message: '请选择入学时间', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
      ],
      email: [
        { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
      ]
    }
    
    // 专业选项
    const majorOptions = [
      { value: '计算机科学与技术', label: '计算机科学与技术' },
      { value: '软件工程', label: '软件工程' },
      { value: '网络工程', label: '网络工程' },
      { value: '信息安全', label: '信息安全' },
      { value: '数据科学与大数据技术', label: '数据科学与大数据技术' },
      { value: '电子信息工程', label: '电子信息工程' },
      { value: '人工智能', label: '人工智能' },
      { value: '物联网工程', label: '物联网工程' },
      { value: '智能科学与技术', label: '智能科学与技术' },
      { value: '信息管理与信息系统', label: '信息管理与信息系统' },
      { value: '电子商务', label: '电子商务' },
      { value: '物流管理', label: '物流管理' },
      { value: '市场营销', label: '市场营销' },
      { value: '会计学', label: '会计学' },
      { value: '财务管理', label: '财务管理' },
      { value: '国际经济与贸易', label: '国际经济与贸易' },
      { value: '法学', label: '法学' },
      { value: '英语', label: '英语' },
      { value: '数学与应用数学', label: '数学与应用数学' },
      { value: '物理学', label: '物理学' },
      { value: '化学', label: '化学' },
      { value: '其他', label: '其他' }
    ]
    
    // 班级选项
    const classOptions = [
      { value: '计科2301', label: '计科2301' },
      { value: '计科2302', label: '计科2302' },
      { value: '软工2301', label: '软工2301' },
      { value: '软工2302', label: '软工2302' },
      { value: '网工2301', label: '网工2301' },
      { value: '信安2301', label: '信安2301' },
      { value: '数据2301', label: '数据2301' },
      { value: '信工2501', label: '信工2501' },
      { value: '信工2502', label: '信工2502' },
      { value: '信工2503', label: '信工2503' },
      { value: '信工2504', label: '信工2504' },
      { value: '信工2505', label: '信工2505' },
      { value: '信工2506', label: '信工2506' },
      { value: '信工2507', label: '信工2507' },
      { value: '计算机2501', label: '计算机2501' },
      { value: '计算机2502', label: '计算机2502' },
      { value: '计算机2503', label: '计算机2503' },
      { value: '计算机2504', label: '计算机2504' },
      { value: '计算机2505', label: '计算机2505' },
      { value: '计算机2506', label: '计算机2506' },
      { value: '计算机2507', label: '计算机2507' },
      { value: '其他', label: '其他' }   
    ]
    
    // 状态选项
    const statusOptions = [
      { value: '在校', label: '在校' },
      { value: '毕业', label: '毕业' },
      { value: '休学', label: '休学' },
      { value: '退学', label: '退学' }
    ]
    
    // 对话框标题
    const dialogTitle = computed(() => {
      return isEdit.value ? '编辑学生' : '添加学生'
    })
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        '在校': 'success',
        '毕业': 'info',
        '休学': 'warning',
        '退学': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 移除模拟数据源，改为使用API调用

    // 加载表格数据
    const loadTableData = async () => {
      tableLoading.value = true
      try {
        // 构建查询参数
        const params = {
          page: pagination.currentPage - 1, // 后端从0开始
          size: pagination.pageSize,
          studentId: searchForm.studentId || undefined,
          name: searchForm.name || undefined,
          major: searchForm.major || undefined,
          className: searchForm.className || undefined,
          status: searchForm.status || undefined
        }
        
        // 调用API获取学生列表
        const response = await getStudentList(params)
        
        if (response.code === 200) {
          tableData.value = response.data.content || []
          pagination.total = response.data.totalElements || 0
        } else {
          ElMessage.error(response.message || '加载数据失败')
        }
        
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        tableLoading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1
      loadTableData()
    }
    
    // 重置搜索
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      handleSearch()
    }
    
    // 显示添加对话框
    const showAddDialog = () => {
      isEdit.value = false
      // 先重置表单数据
      resetForm()
      // 使用nextTick确保DOM更新后再显示对话框
      nextTick(() => {
        dialogVisible.value = true
      })
    }
    
    // 编辑
    const handleEdit = (row) => {
      isEdit.value = true
      dialogVisible.value = true
      // 复制所有字段到表单数据
      Object.keys(formData).forEach(key => {
        formData[key] = row[key]
      })
      // 添加id字段用于更新时识别
      formData.id = row.id
    }
    
    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除学生 ${row.name} 的信息吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 调用删除API
        const response = await deleteStudent(row.studentId)
        
        if (response.code === 200) {
          ElMessage.success('删除成功')
          loadTableData()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    // 批量删除
    const handleBatchDelete = async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedRows.value.length} 条数据吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 调用批量删除API
        const selectedIds = selectedRows.value.map(row => row.studentId)
        const response = await batchDeleteStudents(selectedIds)
        
        if (response.code === 200) {
          ElMessage.success('批量删除成功')
          loadTableData()
        } else {
          ElMessage.error(response.message || '批量删除失败')
        }
        
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }
    }
    
    // 导出
    const handleExport = () => {
      ElMessage.info('导出功能开发中...')
    }
    
    // 导入
    const handleImport = () => {
      ElMessage.info('导入功能开发中...')
    }
    
    // 选择变化
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }
    
    // 分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      loadTableData()
    }
    
    // 当前页变化
    const handleCurrentChange = (page) => {
      pagination.currentPage = page
      loadTableData()
    }
    
    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        const valid = await formRef.value.validate()
        if (!valid) return
        
        submitLoading.value = true
        
        let response
        if (isEdit.value) {
          // 编辑模式：更新现有数据
          response = await updateStudent(formData.studentId, formData)
        } else {
          // 新增模式：添加新数据
          response = await addStudent(formData)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
          dialogVisible.value = false
          loadTableData()
        } else {
          ElMessage.error(response.message || '操作失败')
        }
        
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 关闭对话框
    const handleDialogClose = () => {
      dialogVisible.value = false
      // 延迟重置表单，确保对话框完全关闭后再清空
      nextTick(() => {
        resetForm()
      })
    }
    
    // 重置表单
    const resetForm = () => {
      // 清空所有表单字段
      formData.id = null
      formData.studentId = ''
      formData.name = ''
      formData.gender = ''
      formData.birthDate = null  // 日期字段设置为null
      formData.major = ''
      formData.className = ''
      formData.phone = ''
      formData.email = ''
      formData.enrollmentDate = null  // 日期字段设置为null
      formData.status = '在校'
      
      // 重置表单验证状态
      if (formRef.value) {
        formRef.value.resetFields()
      }
      
      console.log('表单已重置:', formData)
    }
    
    // 页面加载
    onMounted(() => {
      loadTableData()
    })
    
    return {
      formRef,
      tableLoading,
      submitLoading,
      dialogVisible,
      isEdit,
      selectedRows,
      searchForm,
      pagination,
      tableData,
      formData,
      formRules,
      majorOptions,
      classOptions,
      statusOptions,
      dialogTitle,
      getStatusType,
      handleSearch,
      handleReset,
      showAddDialog,
      handleEdit,
      handleDelete,
      handleBatchDelete,
      handleExport,
      handleImport,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleSubmit,
      handleDialogClose,
      canCreate,
      canEdit,
      canDelete
    }
  }
}
</script>

<style lang="scss" scoped>
.student-management {
  .page-title {
    margin-bottom: 20px;
    
    h1 {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0;
    }
  }
  
  .search-conditions {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .search-form {
      .search-fields {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        margin-bottom: 20px;
        
        .el-form-item {
          margin-bottom: 0;
          margin-right: 0;
        }
      }
      
      .search-actions {
        display: flex;
        justify-content: center;
        gap: 12px;
      }
    }
  }
  
  .action-bar {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .student-list {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    
    .el-table {
      margin-bottom: 16px;
      
      :deep(.el-table__header) {
        th {
          background: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }
      
      :deep(.el-table__row) {
        &:hover {
          background: #f8f9ff;
        }
      }
    }
    
    .pagination-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .total-info {
        color: #606266;
        font-size: 14px;
      }
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .student-management {
    .search-conditions {
      .search-form {
        .search-fields {
          flex-direction: column;
          gap: 12px;
          
          .el-form-item {
            margin-bottom: 0;
            margin-right: 0;
          }
        }
        
        .search-actions {
          margin-top: 16px;
        }
      }
    }
    
    .action-bar {
      flex-direction: column;
      
      .el-button {
        width: 100%;
      }
    }
    
    .student-list {
      padding: 16px;
      overflow-x: auto;
    }
  }
}
</style>
